#include "TextBox.h"

TextBox::TextBox(Text* text)
	: _text(text)
{
	if (_shader == nullptr)
	{
		_shader = new GLProgram("Text box shader");
		_shader->attach(GL_VERTEX_SHADER, "shaders/textbox.vert");
		_shader->attach(GL_FRAGMENT_SHADER, "shaders/textbox.frag");
		_shader->link();

		_shaderUniformLocations.color = _shader->getUniformLocation("color");
		_shaderUniformLocations.pOrigin = _shader->getUniformLocation("pOrigin");
		_shaderUniformLocations.invImageSize = _shader->getUniformLocation("invImageSize");
	}
	_vao = new GLVertexArray();
	_vbo = GLBuffer::newMutable(GL_ARRAY_BUFFER, sizeof(GLfloat) * 16, 0, GL_DYNAMIC_DRAW);
	_vao->attach(_vbo, 0, 4, GL_FLOAT);

	updateBounds();
}

void TextBox::setWindowSize(float width, float height)
{
	_shader->use();
	glUniform2f(_shaderUniformLocations.invImageSize, 1.f / width, 1.f / height);
}

Text* TextBox::getText()
{
	return _text;
}

void TextBox::render()
{
	if (_width != _text->getWidth()
		|| _height != _text->getHeight())
	{
		updateBounds();
	}

	_shader->use();

	glUniform2f(_shaderUniformLocations.pOrigin, (float)_text->getOriginX(), (float)_text->getOriginY());
	glUniform4f(_shaderUniformLocations.color, 1.f,1.f,1.f,1.f);

	glBindVertexArray(_vao->name);
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glBindVertexArray(0);

	glEnable(GL_BLEND);
	_text->render();
	glDisable(GL_BLEND);
}

void TextBox::updateBounds()
{
	_width = _text->getWidth();
	_height = _text->getHeight();

	GLfloat pos[16] =
	{
		-2.f, -2.f, 0.0f, 1.f,
		_width+2.f, -2.f, 0.0f, 1.f,
		-2.f, _height+2.f, 0.0f, 1.f,
		_width+2.f, _height+2.f, 0.0f, 1.f
	};

	glNamedBufferSubData(_vbo->name, 0, sizeof(GLfloat) * 16, pos);
}

GLProgram* TextBox::_shader = nullptr;
TextBox::TextBoxShaderUniformLocations TextBox::_shaderUniformLocations;